import {createStore} from 'vuex'
import router, {routes} from '@/router'
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";
import createPersistedState from 'vuex-persistedstate'
import {ROLE_MAP} from "@/permission.js";

export default createStore({
    plugins: [
        createPersistedState({
            paths: ['userInfo', 'menuRoutes']
        })
    ],
    state: {
        userInfo: {},
        menuRoutes: [],
    },

    mutations: {
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo
            userInfo.role = ROLE_MAP.get(Number(userInfo.role))
            const route = routes.find(e => e.path === `/${userInfo.role}Home`)
            state.menuRoutes = route?.children.filter(e => e.meta && e.meta.hidden === undefined).map(e => ({
                ...e, path: (route.path + '/' + e.path).replace(/\/+/g, '/')
            }))
        },
        CLEAR_USER_INFO(state) {
            state.userInfo = {}
            state.menuRoutes = []
            localStorage.removeItem('userInfo');
        }
    },

    actions: {
        // 登录
        async login({commit}, loginForm) {
            let userInfo = await request.post('/user/login', loginForm)
            await commit('SET_USER_INFO', userInfo)
            await router.push(`/${userInfo.role}Home`)
            ElMessage.success('登录成功')
        },

        // 退出登录
        async logout({commit}) {
            await commit('CLEAR_USER_INFO')
            await router.push('/login')
            ElMessage.success('退出成功')
        },

        // 获取用户信息
        async getUserInfo({commit}) {
            try {
                const userInfo = await request.get('/user/current')
                await commit('SET_USER_INFO', userInfo)
            } catch (e) {
                localStorage.removeItem('userInfo')
            }
        },
    }
}) 